require('buffer')
require('CCD')

exp_time=16
setpoint=32768
minv=0
maxv=0
range=0
avg=0
flipx=false
flipy=false
swapxy=false

img=buffer.create()
img:allocate(512*512*3)
imgptr=img:ptr()

print('Openning CCD...')
CCD.open()
print('CCD openned.')
while true do
	if quit_flag then break end
	CCD.setexp(0,511,0,511,exp_time)
	CCD.exp()
	while true do
		suspend()
		sts=CCD.status()
		if sts==3 or sts==4 then break end
	end
	minv,maxv,range,avg,point_size,point_value,point_x,point_y=CCD.getdata(imgptr,512,512)
	img:flipimage(512,512,3,flipx,flipy,swapxy)
	exp_time=exp_time*setpoint/maxv
	--exp_time=8192
	if exp_time<1 then exp_time=1 elseif exp_time>100000 then exp_time=100000 end
end
print('Closing CCD...')
CCD.close()
print('CCD closed.')
